import React, { useEffect, useState, useRef } from 'react';
import { EditOutlined, PlusOutlined, CopyOutlined, CalendarOutlined, UnorderedListOutlined, DeleteOutlined } from '@ant-design/icons';
import { connect } from 'dva';
import { history } from 'umi';
import { Card, Button, Form, message, Row, Col, Select, Radio, Divider, DatePicker } from 'antd';
import FullCalendar from '@fullcalendar/react'
import dayGridPlugin from '@fullcalendar/daygrid'
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import cnLocale from '@fullcalendar/core/locales/zh-cn';
import styles from './style.less';
import { PageHeaderWrapper, RouteContext } from '@ant-design/pro-layout';
import db from '@/utils/localstorage';
import moment from 'moment';
import LessonList from '@/pages/lesson/list'
import SchedulePrivate from '@/components/SchedulePrivate'
import ProTable from '@ant-design/pro-table';
import { queryPrivateSchedule, batchRemoveSchedule, removeSchedule } from './service';
import { HasPermission } from '@/components/AuthComponent/HasPermission';
const AuthButton = HasPermission(Button);
const AuthDivider = HasPermission(Divider);
const format = 'HH:mm';
const FormItem = Form.Item;
const { RangePicker } = DatePicker;

const formItemLayout = {
  labelCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 5,
    },
  },
  wrapperCol: {
    xs: {
      span: 24,
    },
    sm: {
      span: 18,
    },
    md: {
      span: 18,
    },
  },
};

/**
 * 私教周排期表 
 * 1.日期问题：每次翻页都是一周时间 
 * @param {*} props 
 */
function getCurrWeekDays() {
  let date = []
  date.push(moment().weekday(0).format('YYYY-MM-DD'))
  date.push(moment().weekday(1).format('YYYY-MM-DD'))
  date.push(moment().weekday(2).format('YYYY-MM-DD'))
  date.push(moment().weekday(3).format('YYYY-MM-DD'))
  date.push(moment().weekday(4).format('YYYY-MM-DD'))
  date.push(moment().weekday(5).format('YYYY-MM-DD'))
  date.push(moment().weekday(6).format('YYYY-MM-DD'))
  return date
}

const Schedule = props => {
  const { dispatch, coachList, shopList, courseList } = props;
  const [form] = Form.useForm();
  const actionRef = useRef();
  const fullRef = useRef();
  let calendarComponentRef = React.createRef();
  const [calendarWeekends, setCalendarWeekends] = React.useState(true);
  const [calendarEvents, setCalendarEvents] = React.useState([]);
  const [tabActiveKey, setTabActiveKey] = React.useState("schedule");
  const [type, setType] = React.useState("W");
  const [formValues, setFormValues] = React.useState({});
  const [weekList, setWeekList] = useState(getCurrWeekDays());
  const [classTableInfoMap, setClassTableInfoMap] = useState({});
  const [showType, setShowType] = React.useState("C");
  const [nowDate, setNowDate] = React.useState(moment().format('YYYY-MM'));

  const columns = [
    {
      title: '课程',
      dataIndex: 'courseName',
    },
    {
      title: '教练',
      dataIndex: 'coachName',
    },
    {
      title: '课程时间',
      dataIndex: 'timePeriod',
      hideInSearch: true,
      render: (text, record) => {
        if (record.date) {
          return record.date.concat(" ").concat(text)
        } else {
          return text
        }
      }
    },
    {
      title: '预约人数',
      dataIndex: 'bookingNum',
      hideInSearch: true
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <AuthButton auth={[`lesson:schedule:detail`]} type="link" onClick={() => go2Detail(record)}>详情</AuthButton>
          <AuthDivider auth={['lesson:schedule:detail', `lesson:schedule:update`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`lesson:schedule:update`]} type="link" onClick={() => go2Edit(record)}>编辑</AuthButton>
          <AuthDivider auth={['lesson:schedule:update', `lesson:schedule:delete`]} type="vertical"></AuthDivider>
          <AuthButton auth={[`lesson:schedule:delete`]} type="link" onClick={() => handleRemove(record)}>删除</AuthButton>
        </>
      ),
    },
  ];

  const go2Detail = (record) => {
    history.push(`/sign/reservation/detail/${record.id}`);
  }

  const go2Edit = (record) => {
    history.push(`/lesson/private/edit/${record.id}`);
  }
  const loadWeekEvent = (values) => {
    let params = {
      type: '2',
      classType: '3'
    }
    if (values.startDate) {
      params.startDate = values.startDate
    } else {
      params.startDate = weekList[0]
    }
    if (values.coachId) {
      params.coachId = values.coachId
    }
    if (values.venueId) {
      params.venueId = values.venueId
    }
    dispatch({
      type: 'cubePrivate/classTableInfoList',
      payload: {
        ...params
      }
    }).then((result) => {
      let _classTableInfoMap = {}
      result.map((item) => {
        if (_classTableInfoMap[item.date]) {
          _classTableInfoMap[item.date].push(item)
        } else {
          _classTableInfoMap[item.date] = []
          _classTableInfoMap[item.date].push(item)
        }
      })
      setClassTableInfoMap(_classTableInfoMap)
    })
  }
  const loadEvent = (values) => {
    let params = {
      type: '3',
      classType: '3',
    }
    if (values.coachId) {
      params.coachId = values.coachId
    }
    if (values.venueId) {
      params.venueId = values.venueId
    }
    params.startDate = values.startDate || formValues.startDate || moment().format('YYYY-MM')
    dispatch({
      type: 'cubePrivate/classTableInfoList',
      payload: {
        ...params
      }
    }).then((result) => {
      let _calendarEvents = []
      result.map((item) => {
        let date = item.date.concat(' ').concat(item.openingTimeHour).concat(':').concat(item.openingTime)
        _calendarEvents.push({
          id: item.id,
          title: item.courseName,
          start: new Date(moment(date).format('YYYY-MM-DD HH:mm:ss')),
          // allDay:true
          // end:new Date(moment().format('YYYY-MM-DD HH:mm:ss'))
        })
      })
      setCalendarEvents(_calendarEvents)
    })
  }
  useEffect(() => {
    if (dispatch) {
      dispatch({
        type: 'cubePrivate/fetchCoach',
        payload: {
          empType: 2,
        },
      })
      dispatch({
        type: 'cubePrivate/selectAllCourse',
        payload: {
          courseType: "3"
        },
      })
      dispatch({
        type: 'cubePrivate/fetchShopList',
        payload: {
          userId: db.get("user").userId
        }
      })
      loadWeekEvent(formValues)
    }
    if (props.location.query) {
      let tabActiveKey = props.location.query.tabActiveKey;
      if (tabActiveKey) {
        setTabActiveKey(tabActiveKey)
      }
    }
  }, []);

  /**
   * 切换课程还是课表
   * @param {*} tabActiveKey 
   */
  const onTabChange = tabActiveKey => {
    setTabActiveKey(tabActiveKey)
  };

  const gotoPast = () => {
    let calendarApi = calendarComponentRef.current.getApi();
    calendarApi.gotoDate("2000-01-01"); // call a method on the Calendar object
  };

  /**
   * 生成排期
   */
  const addSchedule = () => {
    history.push(`/lesson/private/save`);
  }

  /**
   * 月周课表切换
   * @param {*} e 
   */
  const typeChange = (e) => {
    setType(e.target.value);
    if ('W' == e.target.value) {
      loadWeekEvent(formValues)
    } else if ('M' == e.target.value) {
      loadEvent(formValues)
    }
  }

  /**
  * 课表数据查询
  */
  const handleSearch = values => {
    setFormValues(values);
    if ('M' == type) {
      loadEvent(values);
    } else if ('W' == type) {
      loadWeekEvent(values);
    }
  }

  /**
   * 重置查询
   */
  const handleReset = () => {
    form.resetFields();
    setFormValues({});
    if ('M' == type) {
      loadEvent({});
    } else if ('W' == type) {
      loadWeekEvent({});
    }

  }
  /**
   * 上一周
   * @param {*} date 
   */
  const prev = (date) => {
    setWeekList(date)
    formValues.startDate = date[0]
    setFormValues(formValues)
    loadWeekEvent({
      startDate: date[0]
    })
  }

  /**
   * 下一周
   * @param {*} date 
   */
  const next = (date) => {
    setWeekList(date)
    formValues.startDate = date[0]
    setFormValues(formValues)
    loadWeekEvent({
      startDate: date[0]
    })
  }

  /**
  * 日历和列表切换
  * @param {*} type 
  */
  const changeShowType = type => {
    setShowType(type);
  }

  const goDetail = (e) => {
    let id = e.event.id;
    history.push(`/sign/reservation/detail/${id}`);
  }

  const action = tabActiveKey == 'schedule' ? (
    <RouteContext.Consumer>
      {({ }) => {
        return (
          <>
            <AuthButton auth={[`lesson:schedule:add:schedule`]} icon={<PlusOutlined />} type="primary" onClick={addSchedule}>添加排期</AuthButton>
            {/* <AuthButton auth={[`lesson:schedule:copy:schedule`]} icon={<CopyOutlined />} onClick={() => { }}>复制课表</AuthButton> */}
            {
              showType == 'C' && <Button icon={<CalendarOutlined />} onClick={() => changeShowType('L')}>日历</Button>
            }
            {
              showType == 'L' && <Button icon={<UnorderedListOutlined />} onClick={() => changeShowType('C')}>列表</Button>
            }
          </>
        );
      }}
    </RouteContext.Consumer>
  ) : "";
  /**
    * 
    * @param {*} selectedRows 
    */
  const handleBatchRemove = async selectedRows => {
    const hide = message.loading('正在删除');
    if (!selectedRows) return true;

    try {
      let result = await batchRemoveSchedule({
        ids: selectedRows.map(row => row.id),
      });
      hide();
      if (result.code == 0) {
        message.success('删除成功，即将刷新');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      } else {
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };

  const handleRemove = async record => {
    const hide = message.loading('正在删除');
    try {
      let result = await removeSchedule({
        id: record.id,
      });
      hide();
      if (result.code == 0) {
        message.success('删除成功，即将刷新');
        if (actionRef.current) {
          actionRef.current.reload();
        }
        return true;
      } else {
        message.success(result.message);
        return false;
      }
    } catch (error) {
      hide();
      message.error('删除失败，请重试');
      return false;
    }
  };
  return (
    <PageHeaderWrapper extra={action}
      tabActiveKey={tabActiveKey}
      onTabChange={onTabChange}
      tabList={[
        {
          key: 'schedule',
          tab: '私教排班',
        },
        {
          key: 'lesson',
          tab: '私教课程',
        }
      ]}>
      {
        (tabActiveKey == 'schedule' && showType == 'L') && <ProTable
          actionRef={actionRef}
          rowKey="id"
          toolBarRender={(action, { selectedRows }) => [
            <AuthButton auth={[`lesson:schedule:batch:delete`]} onClick={() => handleBatchRemove(selectedRows)}>批量删除 <DeleteOutlined /></AuthButton>
          ]}
          tableAlertRender={({ selectedRowKeys, selectedRows }) => (
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowKeys.length}
              </a>{' '}
              项
            </div>
          )}
          request={params => {
            let _params = {
              pageNum: params.current,
              ...params,
              classType: "3",
              type: "3"
            }
            delete _params.current
            return queryPrivateSchedule(_params)
          }}
          postData={result => result.list}
          columns={columns}
          rowSelection={{}}
        />
      }
      {
        (tabActiveKey == 'schedule' && showType == 'C') &&
        <>
          <Card style={{ marginBottom: 24 }}>
            <Form form={form} name="basic" onFinish={handleSearch} layout="inline">
              <Row gutter={{ md: 8, lg: 24, xl: 48 }} style={{ width: '100%' }}>
                {
                  type == 'M' && <Col md={6} sm={24} >
                    <FormItem label="时间" name="date">
                      <RangePicker picker="month" style={{ width: '100%' }} />
                    </FormItem>
                  </Col>
                }
                {
                  type == 'W' && <Col md={6} sm={24} >
                    <FormItem label="时间" name="date">
                      <RangePicker style={{ width: '100%' }} />
                    </FormItem>
                  </Col>
                }
                <Col md={6} sm={24} >
                  <FormItem label="课程" name="courseId">
                    <Select placeholder="请选择" style={{ width: '100%' }}
                      showSearch
                      filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {
                        courseList && courseList.map((item, index) => <Select.Option value={item.id} key={index}>{item.courseName}</Select.Option>)
                      }
                    </Select>
                  </FormItem>
                </Col>
                {/* <Col md={8} sm={24}>
                  <FormItem label="场馆" name="venueId">
                  <Select placeholder="请选择" style={{ width: '100%' }} 
                    showSearch
                    filterOption={(input, option) =>
                      option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                    }
                    >
                      {
                          shopList&&shopList.map((item,index)=> <Select.Option value={item.id} key={index}>{item.name}</Select.Option>)
                      }
                    </Select>
                  </FormItem>
                </Col> */}
                <Col md={6} sm={24}>
                  <FormItem label="教练" name="coachId">
                    <Select placeholder="请选择" style={{ width: '100%' }}
                      showSearch
                      filterOption={(input, option) =>
                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {
                        coachList && coachList.map((item, index) => <Select.Option value={item.userId} key={index}>{item.name}</Select.Option>)
                      }
                    </Select>
                  </FormItem>
                </Col>
                <Col md={6} sm={24}>
                  <span className={styles.submitButtons}>
                    <Button type="primary" htmlType="submit">查询</Button>
                    <Button style={{ marginLeft: 8 }} onClick={handleReset}>重置</Button>
                  </span>
                </Col>
              </Row>
            </Form>
          </Card>
          <Card bordered={false} className={styles.cardFc}>
            <Radio.Group value={type} buttonStyle="solid" style={{ float: 'right' }} onChange={typeChange}>
              <Radio.Button value="W">周</Radio.Button>
              <Radio.Button value="M">月</Radio.Button>
            </Radio.Group>
            {
              type == 'M' && <FullCalendar
                defaultView="dayGridMonth"
                header={{
                  left: "prev,next",
                  center: "title",
                  right: "",
                }}
                slotDuration='01:00:00'
                slotLabelFormat={[
                  { month: 'long', year: 'numeric' },
                  { weekday: 'short' },
                  {
                    hour: '2-digit',
                    minute: '2-digit',
                    meridiem: false,
                    hour12: false
                  }
                ]}
                minTime='07:00:00'
                maxTime='20:00:00'
                eventLimit={3}
                handleWindowResize={true}
                // slotEventOverlap={false}
                allDaySlot={true}
                // allDayDefault={true}
                fixedWeekCount={false}
                showNonCurrentDates={false}
                locale={cnLocale}
                plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
                ref={calendarComponentRef}
                weekends={calendarWeekends}
                events={calendarEvents}
                ref={fullRef}
                eventClick={(e) => goDetail(e)}
                datesRender={(view, el) => {
                  let newDate = moment(view.view.activeStart).format('YYYY-MM')
                  formValues.startDate = newDate;
                  setFormValues(formValues)
                  loadEvent({
                    ...formValues
                  })
                }}
              />
            }
            {
              type == 'W' && <SchedulePrivate prev={prev} next={next} weekList={weekList} classTableInfoMap={classTableInfoMap} />
            }
          </Card>
        </>
      }
      {
        tabActiveKey == 'lesson' && <LessonList courseType={3} />
      }
    </PageHeaderWrapper>
  )
}

export default connect(({ loading, cubePrivate }) => ({
  coachList: cubePrivate.coachList,
  shopList: cubePrivate.shopList,
  courseList: cubePrivate.courseList
}))(Schedule);